﻿using Curry.Forum.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System.Text;
using System.Configuration;
using Curry.Forum.Command.Handler.AutoFac;
using Curry.Forum.Command.Handler.CommandHandler;
using Newtonsoft.Json;

namespace Curry.Forum.Api.Controllers
{
    [RoutePrefix("api/Home")]
    public class HomeController : ApiController
    {
        [HttpPost]
        [Route("Login")]
        /// <summary>
        /// 这是生成JWT Token方法的地方，一般应放在登录的Action下
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public LoginResult Login([FromBody]LoginRequest request)
        {
            LoginResult rs = new LoginResult();
            
            var userInfo = AutofacExt.GetFromFac<HomeHandler>().Login(request.UserName, request.Password);
            if (userInfo.RtnCode == 1)
            {
                AuthInfo info = new AuthInfo { UserName = JsonConvert.SerializeObject(userInfo.PostData), IsAdmin = true };
                try
                {
                    byte[] key = Encoding.Default.GetBytes(ConfigurationManager.AppSettings["SecureKey"]);

                    //secret需要加密
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    IJsonSerializer serializer = new JsonNetSerializer();
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                    var token = encoder.Encode(info, key);

                    rs.Message = userInfo.ErrorMsg;
                    rs.Token = token;
                    rs.Success = true;
                }
                catch (Exception ex)
                {
                    rs.Message = ex.Message;
                    rs.Success = false;
                }
            }
            else
            {
                rs.Message = userInfo.ErrorMsg;
                rs.Success = false;
            }
            return rs;
        }
    }
}
